import com.atguigu.ggkt.utils.Base64FileConversion;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse;

import java.io.File;
import java.io.IOException;

/**
 * JSAPI 下单为例
 * https://github.com/wechatpay-apiv3/wechatpay-java/blob/main/service/src/example/java/com/wechat/pay/java/service/QuickStart.java
 * */
public class QuickStart {

    public static WechatPayConfigDemo payConfigDemo = null;
    static {
        try {
            // 从 nacos 加载配置
            payConfigDemo = WechatJsapiPayWithNacos.createFromNacos();
            File file = new File(payConfigDemo.getPrivateKeyPath());
            // 把base64字符串转成文件
            Base64FileConversion.decodeBase64ToFile(payConfigDemo.getSignPem(), file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /** 商户号 */
    public static String merchantId = payConfigDemo.getMchId1();
    /**  appid */
    public static String myAppId = payConfigDemo.getMpAppId();

    /** 商户API私钥路径 */
    public static String privateKeyPath = payConfigDemo.getPrivateKeyPath();

    /** 商户API证书证书序列号 */
    public static String merchantSerialNumber = payConfigDemo.getMerchantSerialNumber();

    /** 商户APIV3密钥 */
    public static String apiV3Key = payConfigDemo.getApiV3Key();

    public static void main(String[] args) {

        // 使用自动更新平台证书的RSA配置
        // 一个商户号只能初始化一个配置，否则会因为重复的下载任务报错
        Config config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId)
                        .privateKeyFromPath(privateKeyPath)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3Key)
                        .build();
        JsapiService service = new JsapiService.Builder().config(config).build();
        // request.setXxx(val)设置所需参数，具体参数可见Request定义
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(1);
        request.setAmount(amount);
        request.setAppid(myAppId);
        request.setMchid(merchantId);
        request.setDescription("测试商品标题");
        request.setNotifyUrl("https://wedev.tony16.fun/api/order/wxPay/notify");
        request.setOutTradeNo("20240818131226473P000000021");
        Payer payer = new Payer();
        payer.setOpenid("oOcfb6Lo30hqv9AUIqm0l91adSWA");
        request.setPayer(payer);
        PrepayResponse response = service.prepay(request);

        System.out.println(">>> getPrepayId: "+ response.getPrepayId());
    }
}
